package com.vvv.designpattern.bridge.function;

import com.vvv.designpattern.pojo.UserInfo;
import com.vvv.designpattern.repo.UserRepository;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author vvv
 * @date 2023-11-16 14 21
 * discription 右路的中间层，作用是抽象出公共的代码，和让子类有选择性的去实现接口的方法
 */
public abstract class AbstractRegisterLoginFunc implements RegisterLoginFuncInterface {

    /**
     * 通用的普通登录
     * @param account
     * @param password
     * @param userRepository
     * @return
     */
    protected String commonLogin(String account, String password, UserRepository userRepository) {
        UserInfo userInfo = userRepository.findByUserNameAndUserPassword(account, password);
        if (userInfo == null) {
            return "account / password ERROR!";
        }
        return "Login Success";
    }

    /**
     * 通用的普通注册
     * @param userInfo
     * @param userRepository
     * @return
     */
    protected String commonRegister(UserInfo userInfo, UserRepository userRepository) {
        if (commonCheckUserExists(userInfo.getUserName(), userRepository)) {
            throw new RuntimeException("User already registered");
        }
        userInfo.setCreateDate(new Date());
        userRepository.save(userInfo);
        return "Register Success";
    }

    /**
     * 通用的检查用户是否存在
     * @param userName
     * @param userRepository
     * @return
     */
    protected boolean commonCheckUserExists(String userName, UserRepository userRepository) {
        UserInfo userInfo = userRepository.findByUserName(userName);
        if (userInfo == null) {
            return false;
        }
        return true;
    }

    @Override
    public String login(String account, String password) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String register(UserInfo userInfo) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean checkUserExists(String username) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String login3rd(HttpServletRequest request) {
        throw new UnsupportedOperationException();
    }
}
